/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package drinkcounter;

import com.google.inject.Inject;
import com.google.inject.Provider;
import drinkcounter.model.Participant;
import drinkcounter.model.ParticipantHistory;
import drinkcounter.model.Party;
import drinkcounter.model.PartyHistory;
import java.util.Date;
import java.util.List;
import javax.cache.Cache;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author paloniemit
 */
public class HistoryServiceImpl implements HistoryService{

    private static final Logger log = LoggerFactory.getLogger(DrinkCounterServiceImpl.class);

    @Inject
    private Provider<EntityManager> emProvider;
    @Inject
    private Cache cache;

    @Override
    public List<PartyHistory> getPartyHistory(String partyId) {
        EntityManager em = emProvider.get();
        try{
            Query q = em.createNamedQuery("PartyHistory.byPartyId");
            q.setParameter("partyId", partyId);
            List<PartyHistory> histories = q.getResultList();
            for (PartyHistory partyHistory : histories) {
                for (ParticipantHistory participantHistory : partyHistory.getParticipants()) {
                    // TODO: This is here to fix problems with lazy loading, we should open entity manager for each requets...
                    participantHistory.getParticipantName();
                }
            }
            return histories;
        }finally{
            em.close();
        }
    }

    @Override
    public void takeHistorySnapshot(String partyId) {
        log.info("Taking history snapshot for party {}", partyId);
        cache.remove("history-"+partyId);
        EntityManager em = emProvider.get();
        try{
            Query partyQuery = em.createNamedQuery("Party.byId");
            partyQuery.setParameter("id", partyId);
            Party party = (Party) partyQuery.getSingleResult();
            PartyHistory snapshot = new PartyHistory();
            snapshot.setPartyId(partyId);
            snapshot.setSnapshotTime(new Date());
            for (Participant participant : party.getParticipants()) {
                ParticipantHistory participantSnapshot = new ParticipantHistory();
                participantSnapshot.setAlcoholLevel(participant.getPromilles());
                participantSnapshot.setParticipantName(participant.getName());
                participantSnapshot.setTotalDrinks(participant.getTotalDrinks());
                snapshot.addParticipantHistory(participantSnapshot);
            }
            em.persist(snapshot);
        }finally{
            em.close();
        }
    }

}
